//
//  MasterViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 17/5/5.
//  Copyright © 2017年 Li Xiangyang. All rights reserved.
//

import UIKit

class MasterViewController: UITableViewController,UISearchBarDelegate {

    var detailViewController: DetailViewController? = nil
    var gongdanList = [TwERPGongdan]()

    @IBOutlet var cphSearchBar: UISearchBar!
    @IBOutlet var addButton: UIBarButtonItem!

    @IBOutlet var gdListView: UITableView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //self.navigationItem.leftBarButtonItem = self.editButtonItem()

        //let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:)))
        //self.navigationItem.rightBarButtonItem = addButton
        if let split = self.splitViewController {
            let controllers = split.viewControllers
            self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
            detailViewController?.masterVTC = self
        }
        TwERPJsonAgent.setHost(UserDefaults.standard.string(forKey: "TWERPHostForMobile"))
        TwERPJsonAgent.initReachability()
    
        if let lCph = UserDefaults.standard.string(forKey: "CurrentCphm") {
            cphSearchBar.text = lCph
            
        }
/*
        DispatchQueue.global(qos: .userInitiated).async {
             let cuser: TwERPUser? =  TwERPUser.loginUser("abc", withPassword: "1")
            DispatchQueue.main.async {
                if cuser == nil {
                    let alert =  UIAlertController(title: "提示", message: "登录不成功，请检查网络连接或用户名口令是否正确！", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
                    self.present(alert, animated: true){print("hello")}
                    
                } else {
                     LoginViewController.currentUser = cuser
                    LoginViewController.gdCategory = TwERPJsonAgent.getCategoryOfGd() as! [String]
                    TwERPJsonAgent.setUserId((cuser?.entityId)!)
                   
                }
                
            }
 
        }
*/
    }

    override func viewWillAppear(_ animated: Bool) {
        self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
        super.viewWillAppear(animated)
    }
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func addGongdan(_ sender: AnyObject) {
        
      //  self.insertNewObject(sender)
        if (LoginViewController.currentUser == nil) {
            let alert =  UIAlertController(title: "提示", message: "请先登录！", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
            
        }
        if ( self.gongdanChananged() != nil) {
            let alert =  UIAlertController(title: "提示", message: "有工单在编辑状态，不能新增!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return

            
        }
        
        if (self.cphSearchBar.text?.characters.count)!<5{
            let alert =  UIAlertController(title: "错误", message: "车牌号码至少要输入5位!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){print("hello")}
            
        } else {
            addButton.isEnabled = false
            let gd :TwERPGongdan = TwERPGongdan.createGongdan(withCphm: cphSearchBar.text)
            addButton.isEnabled = true
            gd.serviceAssistant = LoginViewController.currentUser?.userName
            gongdanList.append(gd)
            gdListView.reloadData()
            detailViewController!.gongdan = gd

        }
        
        

        
    }
    
    func deleteGongdan(gd: TwERPGongdan) -> Void {
        for index in 0...gongdanList.count-1 {
            if gongdanList[index] == gd {
                gongdanList.remove(at: index)
            }
        }
        gdListView.reloadData()
    }
    
    func gongdanEditStateChange () {
        self.gdListView.reloadData()
    }
    
 
    // MARK: - Segues
/*
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
                controller.masterVTC = self
                controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }
*/
    func gongdanChananged() -> TwERPGongdan? {
        for  gd in gongdanList {
            if (gd.operationState ==   GdEdit || gd.operationState == GdInsert || gd.operationState == GdUploading)
            {
                return gd
            }
        }
        return nil
    }
    // MARK: - Table View

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return gongdanList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Gongdan Cell", for: indexPath)

        let gd = gongdanList[indexPath.row]
        
        switch gd.operationState {
        case GdInsert:
            cell.textLabel?.textColor = UIColor.red
            break
        case GdEdit:
            cell.textLabel?.textColor = UIColor.red
            break
        case GdUploading:
            cell.textLabel?.textColor = UIColor.blue
        default:
            cell.textLabel?.textColor = UIColor.black
        }
       
        cell.textLabel!.text = gd.gdNo
        cell.detailTextLabel?.text = gd.category
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let gd = gongdanList[indexPath.row]
        if let controller = detailViewController{
            controller.masterVTC = self
            controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            controller.navigationItem.leftItemsSupplementBackButton = true
            controller.gongdan = gd
        }
    }
  
    func startActivityIndicating ()
    {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        indicator.stopAnimating()
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: indicator)
    
    }
    
    func stopActivityIndicating ()
    {
        navigationItem.rightBarButtonItem = addButton
        
    }


    func loadGongdanBy(cphm: String) -> () {
        
        //判断是否在录音、编辑状态等并提示
        if (gongdanChananged() != nil) {
            let alert =  UIAlertController(title: "提示", message: "有工单在编辑状态，不能加载！", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
        }
      
        startActivityIndicating()
        DispatchQueue.global(qos: .userInitiated).async {
            if let vehToGet: TwERPVehicle? = TwERPVehicle.getByCphm(cphm) {
                self.gongdanList = vehToGet?.getGongdanList() as! [TwERPGongdan]
                 UserDefaults.standard.set(self.cphSearchBar.text, forKey: "CurrentCphm")
            } else {
                DispatchQueue.main.async {
                    self.stopActivityIndicating()
                    let alert =  UIAlertController(title: "提示", message: "系统中无该车牌号！", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
                    self.present(alert, animated: true){}
                }
                return
            }
            
            DispatchQueue.main.async {
                self.stopActivityIndicating()
                if self.gongdanList.count>0 {
                    self.tableView.reloadData()
                    self.detailViewController?.gongdan = self.gongdanList[0]
                } else {
                   
                    let alert =  UIAlertController(title: "提示", message: "该车牌号无维修记录！", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
                    self.present(alert, animated: true){}
                   
                }
                    
            }

            
        }

        

    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let alertMessage = { () -> String? in
            if !TwERPJsonAgent.isServerReachable() {
                return "网络连接不正常,请检查!"
            } else if  (self.cphSearchBar.text?.characters.count)!<5 {
                return "车牌号码至少要输入5位"
            } else if (LoginViewController.currentUser == nil)  {
                return "请先登录！"
            } else if   self.gongdanChananged() != nil {
                return "有工单在编辑状态，请先保存有取消！"
            } else {return nil}}()
        
        {
            let alert =  UIAlertController(title: "提示", message: alertMessage, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
        }
        self.loadGongdanBy(cphm: searchBar.text!)
        
        
    }

}

